package edu.zut.software.identity.controller;

import edu.zut.software.identity.Repository.TeaInfoRepository;
import edu.zut.software.identity.Service.impl.TeaCollegeServiceImpl;
import edu.zut.software.identity.Service.impl.TeaMajorServiceImpl;
import edu.zut.software.identity.Service.impl.TeacherServiceImpl;
import edu.zut.software.identity.domain.*;
import edu.zut.software.identity.utils.JsonUtil;
import edu.zut.software.identity.utils.WXAPIUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author Weining
 */
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    TeacherServiceImpl teacherService;
    TeaCollegeServiceImpl teaCollegeService;
    TeaMajorServiceImpl teaMajorService;
    public TeaInfoRepository teaInfoRepository;
    @Autowired
    public void setTeaInfoRepository(TeaInfoRepository teaInfoRepository) {
        this.teaInfoRepository = teaInfoRepository;
    }

    @Autowired
    public void setTeacherService(TeacherServiceImpl teacherService) {
        this.teacherService = teacherService;
    }
    @Autowired
    public void setTeaCollegeService(TeaCollegeServiceImpl teaCollegeService) {
        this.teaCollegeService = teaCollegeService;
    }
    @Autowired
    public void setTeaMajorService(TeaMajorServiceImpl teaMajorService) {
        this.teaMajorService = teaMajorService;
    }
    /**
     * 同步部门(添加所有部门)
     * @return 原未创建而先已经创建部门的json
     */
    @RequestMapping("/createAllTeacherDepartment")
    public String update(){
        StringBuilder data= new StringBuilder();
        boolean collegeSet=true,majorSet=true;
        List<TeaCollege> teaColleges = teaCollegeService.findAll();
        for (TeaCollege teaCollege : teaColleges) {
            if (teaCollege.getWxId()==0){
                createCollege(teaCollege);
                data.append(teaCollege.toString());
                collegeSet=false;
            }
        }
        if (collegeSet){
            logger.info("学院全部创建");
        }
        List<TeaMajor> teaMajors = teaMajorService.findAll();
        for (TeaMajor teaMajor : teaMajors) {
            if (teaMajor.getWxId()==0){
                createMajor(teaMajor);
                data.append(teaMajor.toString());
                majorSet=false;
            }
        }
        if(majorSet){
            logger.info("专业全部创建");
        }
        return data.toString();
    }
    /*
    学院
     */

    /**
     * 查询所有学院
     * @return 学院集合
     */
    @RequestMapping("/f1")
    public List<TeaCollege> findAllC(){
        return teaCollegeService.findAll();
    }

    /**
     * 创建学院
     */
    public void createCollege(TeaCollege teaCollege){
        Map<String,Object> jsonMap= WXAPIUtil.createDepartment(teaCollege.getName(),teaCollege.getWxParentId(),100-teaCollege.getPx());
        if(Integer.parseInt(jsonMap.get("errcode").toString())==0){
            teaCollege.setWxId(Integer.parseInt(jsonMap.get("id").toString()));
            teaCollegeService.save(teaCollege);
            logger.info("创建学院:{},状态:{}",teaCollege.getName(),"成功");
        }
        else{
            logger.info("创建学院:{},状态:{}",teaCollege.getName(),"失败");
        }
    }

    /**
     * 添加学院(手动)
     * @param teaCollege 学院对象
     * @return 添加成功与否,用resp.data取
     */
    @RequestMapping(value = "/addCollege",method = RequestMethod.POST)
    public String addCollege(@RequestBody TeaCollege teaCollege){
        if(teaCollegeService.isExists(teaCollege.getId())){
            return "添加失败";
        }
        Map<String, Object> resMap=WXAPIUtil.createDepartment(teaCollege.getName(),3,100-teaCollege.getPx());
        if(Integer.parseInt(resMap.get("errcode").toString())==0){
            teaCollege.setWxId(Integer.parseInt(resMap.get("id").toString()));
            teaCollege.setWxParentId(3);
            teaCollegeService.save(teaCollege);
            return "添加成功";
        }
        else{
            return resMap.get("errcode").toString();
        }
    }

    /**
     *删除学院
     * @param id 学院id
     * @return 删除是否成功
     */
    @RequestMapping("/deleteCollege/{id}")
    public String deleteCollege(@PathVariable String id) {
        boolean flag=true;
        List<TeaMajor> teaMajorServiceAll = teaMajorService.findAll();
        for (TeaMajor major : teaMajorServiceAll) {
            if (Objects.equals(major.getCollegeId(), id)){
                flag=false;
                return "120";
            }
        }
        String deleteid=String.valueOf(teaCollegeService.findById(id).getWxId());
        Map<String, Object>resMap=WXAPIUtil.deleteDepartment(deleteid);
        if (Integer.parseInt(resMap.get("errcode").toString())==0){
            teaCollegeService.deleteById(id);
            return "删除成功";
        }
        else{
            flag=false;
            return "删除失败";
        }
    }

    /**
     * 更新学院
     * @param teaCollege 更新的对象
     * @return 更新状态
     */
    @RequestMapping("/saveCollege")
    public String updateCollege(@RequestBody TeaCollege teaCollege){
        Map<String, Object> resultMap=WXAPIUtil.updateDepartment(String.valueOf(teaCollegeService.getId(teaCollege.getId())),teaCollege.getName());
        if(Integer.parseInt(resultMap.get("errcode").toString())==0){
            //新建一个变量令其为即将覆盖的学院信息
            TeaCollege oldCollege=teaCollegeService.findById(teaCollege.getId());
            //将老的信息赋值给新的信息,然后使用save方法更新
            teaCollege.setWxId(oldCollege.getWxId());
            teaCollege.setPx(oldCollege.getPx());
            teaCollege.setWxParentId(oldCollege.getWxParentId());
            teaCollegeService.save(teaCollege);
            return "修改成功";
        }
        return "修改失败";
    }

    /**
     *
     * @param id 查询id
     * @return 学院对象
     */
    @RequestMapping("/findCollegeByID/{id}")
    public TeaCollege findCollegeById(@PathVariable String id){
        return teaCollegeService.findById(id);
    }
    /**
     * 分页查询College
     * @param page  页码
     * @param number 每页个数
     * @return Page
     */
    @GetMapping("/searchCollege/{page}/{number}")
    public Page<TeaCollege> searchCollege(@PathVariable Integer page, @PathVariable Integer number) {
        return teaCollegeService.findAll(page-1, number);
    }

    /*
    专业
     */

    /**
     * 查询所有专业
     * @return 专业列表
     */
    @RequestMapping("/f2")
    public  List<TeaMajor> findAllM(){
        return teaMajorService.findAll();
    }

    /**
     * 创建专业
     */
    public void createMajor(TeaMajor teaMajor){
        int majorParentId=teaCollegeService.findById(teaMajor.getCollegeId()).getWxId();
        Map<String,Object> jsonMap= WXAPIUtil.createDepartment(teaMajor.getName(),majorParentId,100-teaMajor.getPx());
        if(Integer.parseInt(jsonMap.get("errcode").toString())==0){
            teaMajor.setWxId(Integer.parseInt(jsonMap.get("id").toString()));
            teaMajorService.save(teaMajor);
            logger.info("创建专业:{},状态:{}",teaMajor.getName(),"成功");
        }
        else{
            logger.info("创建专业:{},状态:{}",teaMajor.getName(),"失败");
        }
    }

    /**
     *
     * @param teaMajor 专业对象
     * @return 添加成功了吗?
     */
    @RequestMapping(value = "/addMajor",method = RequestMethod.POST)
    public String addMajor(@RequestBody TeaMajor teaMajor){
        if (teaMajorService.isExists(teaMajor.getId())){
            return "添加失败";
        }
        int parentId=teaCollegeService.getId(teaMajor.getCollegeId());
        logger.info("{}",teaMajor);
        Map<String, Object> resMap=WXAPIUtil.createDepartment(teaMajor.getName(),parentId,100-teaMajor.getPx());
        if (Integer.parseInt(resMap.get("errcode").toString())==0){
            teaMajor.setWxId(Integer.parseInt(resMap.get("id").toString()));
            teaMajorService.save(teaMajor);
            return "添加成功";
        }
        else{
            return resMap.get("errcode").toString()+" "+resMap.get("errmsg");
        }
    }

    /**
     *删除专业
     * @param id 专业id
     * @return 删除是否成功
     */
    @RequestMapping("/deleteMajor/{id}")
    public String deleteMajor(@PathVariable String id) {
        boolean flag=true;
        List<Teacher> all = teacherService.findAll();

        for (Teacher teacher : all) {
            if (Objects.equals(teacher.getMajorId(), id)){
                flag=false;
                return "请先删除这个部门下所有的教职工";
            }
        }
        String deleteid=String.valueOf(teaMajorService.findById(id).getWxId());
        Map<String, Object>resMap=WXAPIUtil.deleteDepartment(deleteid);
        if (Integer.parseInt(resMap.get("errcode").toString())==0){
            teaMajorService.deleteById(id);
            return "删除成功";
        }
        else{
            flag=false;
            return "删除失败";
        }
    }
    /**
     *
     * @param id 查询id
     * @return 专业对象
     */
    @RequestMapping("/findMajorByID/{id}")
    public TeaMajor findMajorById(@PathVariable String id){
        return teaMajorService.findById(id);
    }
    /**
     * 更新学院
     * @param teaMajor 更新的对象
     * @return 更新状态
     */
    @RequestMapping("/saveMajor")
    public String updateMajor(@RequestBody TeaMajor teaMajor){
        Map<String, Object> resultMap=WXAPIUtil.updateDepartment(String.valueOf(teaMajorService.getId(teaMajor.getId())),teaMajor.getName());
        if(Integer.parseInt(resultMap.get("errcode").toString())==0){
            //新建一个变量令其为即将覆盖的学院信息
            TeaMajor oldMajor = teaMajorService.findById(teaMajor.getId());
            //将老的信息赋值给新的信息,然后使用save方法更新
            teaMajor.setWxId(oldMajor.getWxId());
            teaMajor.setPx(oldMajor.getPx());
            teaMajor.setCollegeId(oldMajor.getCollegeId());
            teaMajorService.save(teaMajor);
            return "修改成功";
        }
        return "修改失败";
    }
    /**
     * 分页查询Major
     * @param page  页码
     * @param number 每页个数
     * @return Page
     */
    @GetMapping("/searchMajor/{page}/{number}")
    public Page<TeaMajor> searchMajor(@PathVariable Integer page, @PathVariable Integer number) {
        return teaMajorService.findAll(page-1, number);
    }


    /*
    教师
     */

    /**
     * 查询所有教师
     * @return 教师集合
     */
    @RequestMapping("/f3")
    public List<Teacher> findAllT(){
        return teacherService.findAll();
    }

    /**
     *
     * @param teacher
     * @return
     */
    @RequestMapping("/createTeacher")
    public String createTeacher(@RequestBody Teacher teacher){
        List<Integer> departmentList=new ArrayList<>();
        departmentList.add(1);
        departmentList.add(3);
        logger.info("部门列表:{}",departmentList);
        logger.info("CollegeId:{} {}",teacher.getCollegeId(),teaCollegeService.getId(teacher.getCollegeId()));
        departmentList.add(teaCollegeService.getId(teacher.getCollegeId()));
        departmentList.add(teaMajorService.getId(teacher.getMajorId()));

        Map<String, Object> teaMap= new HashMap<>();
        teaMap.put("userid",teacher.getId());
        teaMap.put("name",teacher.getName());
        teaMap.put("mobile",teacher.getIphone());
        teaMap.put("order", Arrays.asList(100-teacher.getPx()));
        teaMap.put("department",departmentList);
        if (teaMap.get("mobile")!=null){
            logger.info("注册信息:{}", JsonUtil.toJson(teaMap));
            Map<String, Object>resMap=WXAPIUtil.createContact(JsonUtil.toJson(teaMap));
            if(Integer.parseInt(resMap.get("errcode").toString())==0){
                teacherService.save(teacher);
                return "添加成功";
            }
            else{
                return "返回码"+resMap.get("errcode").toString()+":"+resMap.get("errmsg").toString();
            }
        }

        return "增加失败";
    }
    /**
     * 删除成员
     */
    @RequestMapping("/deletePerson/{id}")
    public String deletePerson(@PathVariable("id") String id){
        boolean flag=true;
//        String wxId=String.valueOf(teacherService.findById(id).getWxId());
        Map<String, Object> resMap = WXAPIUtil.deletePerson(id);
        logger.info("返回值{}",resMap);
        if (Integer.parseInt(resMap.get("errcode").toString())==0){
            teacherService.deleteById(id);
            return "删除成功";
        }
        else{
            flag=false;
            return "删除失败";
        }
    }

    /**
     * 分页查询teacher
     * @param page  页码
     * @param number 每页个数
     * @return Page
     */
    @GetMapping("/searchTeacher/{page}/{number}")
    //  @ResponseBody
    public Page<Teacher> searchTeacher(@PathVariable Integer page, @PathVariable Integer number) {
        return teacherService.findAll(page-1, number);
    }

    /**
     * 获取联动菜单对象
     * @return 一个联动菜单的json
     */
    @RequestMapping("/getLinkedUnit")
    public Map<String,List<TeaMajor>> getLinkedUnit(){
        Map<String,List<TeaMajor>> unitMap = new HashMap<>();
        List<TeaCollege> collegeAll = teaCollegeService.findAll();
        for (TeaCollege teaCollege : collegeAll) {
            //主键是学院部门,值是collegeId是K的id的所有子部门
            unitMap.put(teaCollege.getId(),teaMajorService.findAllByCollegeId(teaCollege.getId()));
        }
        return unitMap;
    }
    @RequestMapping("findByCollegeId/{collegeId}")
    public List<TeaMajor> findByCollegeId(@PathVariable String collegeId ){
        return teaMajorService.findAllByCollegeId(collegeId);
    }

    /**
     * 分页查询视图
     * @param page
     * @param number
     * @param teacherInfo
     * @return
     */
    @PostMapping("/search/{page}/{number}")
    //  @ResponseBody
    public Page<TeacherInfo> search(@PathVariable Integer page, @PathVariable Integer number, @RequestBody TeacherInfo teacherInfo) {
        logger.info("{}","111111111111111111111111111111111111111");
        if (number == null && number.equals(0)) {
            number = 15;
        }
        return teacherService.findAll(page - 1, number, teacherInfo);
    }

    /**
     * 是否存在
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public String findById(@PathVariable("id") String id) {
        boolean exists = teacherService.isExists(id);
        if (exists) {
            return "success";
        } else {
            return "error";
        }

    }

    @RequestMapping("/findTeacherById/{id}")
    public Teacher findTeacherById(@PathVariable String id){
        return teacherService.findById(id);
    }
    /**
     * 添加教职工手机号
     */
    @GetMapping("/modify/{id}/{iphone}")
    public String savePhone(@PathVariable("id") String id, @PathVariable("iphone") String iphone) {
        if (teacherService.isExists(id)){
            Teacher teacher = teacherService.findById(id);
            Date time = new Date();
            teacher.setTime(time);
            teacher.setIphone(iphone);
            teacherService.save(teacher);
            if (Objects.equals(teacher.getIphone(), iphone)) {
                return "success";
            } else {
                return "error";
            }
        }
        else{
            return "error";
        }

    }
    /**
     * 创建成员
     */
    @RequestMapping("/register")
    public void register() {
        boolean flag=true;

        List<Teacher> teachers = teacherService.findAll();
        List<Integer> departmentList = new ArrayList<>();
        Map<String, Object> jsonMap=new HashMap<>();

        for (Teacher teacher : teachers) {
            Map<String, Object> map = new HashMap<String, Object>() {
                {
                    put("userid", teacher.getId());
                    put("name", teacher.getName());
                    put("mobile", teacher.getIphone());
                    put("order", Arrays.asList(10000 - teacher.getPx()));
                    // put("position", userInfo.getZw());
                    // put("gender", userInfo.getXb());
                    //put("to_invite", false);
                }
            };
            departmentList.add(1);
            departmentList.add(3);
            logger.info("部门列表:{}", departmentList);
            logger.info("CollegeId:{} {}", teacher.getCollegeId(), teaCollegeService.getId(teacher.getCollegeId()));
            departmentList.add(teaCollegeService.getId(teacher.getCollegeId()));
            departmentList.add(teaMajorService.getId(teacher.getMajorId()));

            System.out.println(map.get("mobile"));
            if (map.get("mobile") != null) {
                map.put("department", departmentList);
                logger.info("注册信息:{}", JsonUtil.toJson(map));
                 jsonMap= WXAPIUtil.createContact(JsonUtil.toJson(map));
                logger.info("返回信息:{}", JsonUtil.toJson(jsonMap));
                if (Integer.parseInt(jsonMap.get("errcode").toString()) == 0) {
                    //  userInfo.setWx_id(Integer.parseInt(jsonMap.get("id").toString()));
                    teacherService.save(teacher);

                } else {
                    flag=false;

                }
            }
            departmentList.clear();
            jsonMap.clear();
        }

    }
    /**
     * 导入导出
     */
    @GetMapping("/export")
    public ResponseEntity<byte[]> export() throws UnsupportedEncodingException {
        String savePath = "";
        HttpHeaders headers = null;
        ByteArrayOutputStream baos = null;
        List<TeacherInfo> all = teaInfoRepository.findAll();
        HSSFWorkbook workbook = new HSSFWorkbook();   //创建Excel文档
        HSSFSheet sheet = workbook.createSheet("中原工学院教职工信息表");   //创建Excel表单
        //设置表头
        HSSFRow headerRow = sheet.createRow(0);
        HSSFCell cell0 = headerRow.createCell(0);
        cell0.setCellValue("教职工号");
        HSSFCell cell1 = headerRow.createCell(1);
        cell1.setCellValue("姓名");
        HSSFCell cell2 = headerRow.createCell(2);
        cell2.setCellValue("部门");
        HSSFCell cell3 = headerRow.createCell(3);
        cell3.setCellValue("子部门");
        HSSFCell cell4 = headerRow.createCell(4);
        cell4.setCellValue("手机号");
        HSSFCell cell5 = headerRow.createCell(5);
        cell5.setCellValue("wx_id");
        HSSFCell cell6 = headerRow.createCell(6);
        cell6.setCellValue("px");
        //装数据
        for (int i = 0; i < all.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            TeacherInfo info = all.get(i);
            row.createCell(0).setCellValue(info.getId());
            row.createCell(1).setCellValue(info.getTname());
            row.createCell(2).setCellValue(info.getCollegeName());
            row.createCell(3).setCellValue(info.getMajorName());
            row.createCell(4).setCellValue(info.getIphone());
            row.createCell(5).setCellValue(info.getWxId());
            row.createCell(6).setCellValue(info.getPx());
        }
        headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment",
                new String("教职工信息表.xls".getBytes("UTF-8"),"iso-8859-1"));
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        baos = new ByteArrayOutputStream();
        try {
            workbook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(baos.toByteArray(), headers, HttpStatus.CREATED);
    }
    @PostMapping("/import")
    public int importTea(MultipartFile file) {
        //    List<Student> emps=new ArrayList<>();
        int success=0;
        try {
            HSSFWorkbook workbook=new HSSFWorkbook(new POIFSFileSystem(file.getInputStream()));
            int numberOfSheets=workbook.getNumberOfSheets();
            for(int i=0;i<numberOfSheets;i++) {
                HSSFSheet sheet=workbook.getSheetAt(i);
                int physicalNumberOfRows=sheet.getPhysicalNumberOfRows();
                Student student=new Student();
                for(int j=0;j<physicalNumberOfRows;j++){
                    if(j==0){
                        continue;
                    }
                    HSSFRow row=sheet.getRow(j);
                    if(row==null){
                        continue;
                    }
                    int physicalNumberOfCells=row.getPhysicalNumberOfCells();
                    Teacher teacher = new Teacher();
                    for(int k=0;k<physicalNumberOfCells;k++){
                        HSSFCell cell=row.getCell(k);
//                        switch (cell.getCellType()){}
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String cellValue=cell.getStringCellValue();
                        switch (k){
                            case 0: teacher.setId(cellValue);
                                break;
                            case 1:teacher.setName(cellValue);
                                break;
                            case 2:teacher.setCollegeId(cellValue);
                                break;
                            case 3:teacher.setMajorId(cellValue);
                                break;
                            case 4:teacher.setIphone(cellValue);
                                break;
                            case 5:teacher.setPx(Integer.parseInt(cellValue));
                                break;
                        }
                    }
                    Teacher teaTemp=teacherService.save(teacher);
                    logger.info("教师信息{}",teacher);
                    if(teaTemp!= null){
                        success += 1;
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return success;
    }
    @GetMapping("/getCount")
    List<Map<Date, Integer>> getCount() {
        Map<Date, Integer> map = new HashMap<>();
        List<Map<Date, Integer>> mapList = teacherService.getCount();
        return mapList;
    }
}
